import React from 'react'
import './style.less'


class LoadMore extends React.Component {
  constructor(props, context) {
    super(props, context);
  }
  render(){
    const data = this.props.data;
    return (
      <div className="load-more" ref="wrapper">
        {
          this.props.isLoadingMore
          ? <span>加载中...</span>
            : <span onClick={this.loadMoreHandle.bind(this)}>加载更多</span>
        }
      </div>
    );
  }

  loadMoreHandle(){
    // 执行传递过来的loadMore
    this.props.loadMoreFn();
  }

  componentDidMount(){
    const loadMoreFn = this.props.loadMoreFn;
    const wrapper = this.refs.wrapper;
    console.log(wrapper);
    let timeoutId;
    function callback() {
      // console.log('456');
      const top = wrapper.getBoundingClientRect().top;
      // console.log(top);
      const windowHeight = window.screen.height;
      if (top && top < windowHeight) {
        // 当wrapper已经被滚动到暴露在页面之外就触发
        loadMoreFn();
      }
    }
    window.addEventListener('scroll', function () {
      if (this.props.isLoadingMore) {
        return
      }
      if (timeoutId) {
        clearTimeout(timeoutId);
      }
      timeoutId = setTimeout(callback, 50);
    }.bind(this), false);
  }
}

export default LoadMore;